package Tree_a;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: dell
 * Date: 2024-01-15
 * Time: 14:55
 */

import Tree_a.BinaryTree.TreeNode;
public class test {
    public int preIndex = 0;
    public Tree_a.BinaryTree.TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }
    private Tree_a.BinaryTree.TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin, int inend) {
        //递归的出口  不满足这个条件 那么就是没有了左树 或者右树
        if(inbegin > inend) {
            return null;
        }
        //先创建根节点
        TreeNode root = new TreeNode((char) preorder[preIndex]);//根节点

        //找到根节点 所在中序遍历中的位置
        int rootIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);
        preIndex++;
        // 先创建左树 再创建右树   本身是在遍历： 前序遍历
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);

        return root;
    }

    private int findIndex(int[] inorder,int inbegin,int inend,int key) {
        for(int i = inbegin; i <= inend; i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}